//
//  ImageEditContainer.swift
//  TemplateImageEditDemo
//
//  Created by liguandong on 2024/4/11.
//

import Foundation
import UIKit
import SnapKit
/**
 所有模板图编辑区，添加模板，手势控制。
 */
class WallpaperEditView: UIView {
    var onAddImage:((Int)->Void)?
    
    private var editingImageContainer : WallpaperImageContainerView? {
        didSet{
            if editingImageContainer != nil {
                controlView.isHidden = false
                controlView.resetState(editingImageContainer!.photoImageView)
            }else{
                controlView.isHidden = true
            }
        }
    }
    private var imageContainerList = [WallpaperImageContainerView]()
    
    //总背景
    private lazy var bgImageView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    
    //照片墙背景
    private lazy var backImageView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    //添加的素材
    private lazy var subViewParent: UIView = {
        let v = UIView()
        return v
    }()
    
    //照片墙前景
    private lazy var fontImageView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    
    private lazy var controlView: WallpaperCtrlView = {
        let v = WallpaperCtrlView()
        v.isUserInteractionEnabled = true
        v.isHidden = true
        v.onTransformUpate = {[weak self] in
            self?.editingImageContainer?.photoImageView.transform = v.transform
        }
        v.onRemoveViewBlock = {[weak self] in
            if let self = self {
                self.controlView.isHidden = true
                if let imageContainer = self.editingImageContainer {
                    let imageInfo = self.editInfo!.imageInfos[imageContainer.index]
                    imageInfo.showImage = nil
                    imageContainer.setImageInfo(imageInfo)
                }
                self.editingImageContainer = nil

            }
        }
        return v
    }()
    
    private lazy var panGesture: UIPanGestureRecognizer = {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction(_:)))
        return panGesture
    }()
    
    private lazy var pinchGesture: UIPinchGestureRecognizer = {
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinchAction(_:)))
        pinchGesture.delegate = self
        return pinchGesture
    }()

    private lazy var rotateGesture: UIRotationGestureRecognizer = {
        let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotateAction(_:)))
        rotateGesture.delegate = self
        return rotateGesture
    }()
    
    override init(frame:CGRect){
        super.init(frame: frame)
        addSubview(bgImageView)
        addSubview(backImageView)
        addSubview(subViewParent)
        addSubview(fontImageView)
        addSubview(controlView)
        
        bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        backImageView.snp.makeConstraints { make in
            make.width.equalToSuperview()
            make.height.equalTo(backImageView.snp.width).multipliedBy(1.0 / WALLPAPER_TEMPLATE_RATIO)
            make.center.equalToSuperview()
        }
        subViewParent.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        fontImageView.snp.makeConstraints { make in
            make.width.equalToSuperview()
            make.height.equalTo(fontImageView.snp.width).multipliedBy(1.0 / WALLPAPER_TEMPLATE_RATIO)
            make.center.equalToSuperview()
        }
        controlView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        addGestureRecognizer(panGesture)
        addGestureRecognizer(pinchGesture)
        addGestureRecognizer(rotateGesture)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onEmptyViewTap(_:)))
        addGestureRecognizer(tapGesture)

    }
    
    
    private var editInfo : WallpaperEditInfo?
    func setEditInfo(_ editInfo : WallpaperEditInfo){
        self.editInfo = editInfo
        subViewParent.subviews.forEach { subView in
            subView.removeFromSuperview()
        }
        bgImageView.image = editInfo.bgImage
        backImageView.image = editInfo.backImage
        fontImageView.image = editInfo.fontImage
        addImageViews()
    }
    
    private var lastSize = CGSize.zero
    override func layoutSubviews() {
        super.layoutSubviews()
        if subViewParent.subviews.count == 0 {
            addImageViews()
        }else{
            if frame.size != lastSize,let editInfo = editInfo {
                let viewRatio = frame.size.width / frame.size.height
                //宽铺满，image的Frame转化为view的Frame，并且计算模板图和view的高度差，需要位移居中
                let offsetImageY = (WALLPAPER_TEMPLATE_RATIO - viewRatio) * WALLPAPER_TEMPLATE_WIDTH / 2
                let scale = frame.size.width / WALLPAPER_TEMPLATE_WIDTH
                for (i,subView) in subViewParent.subviews.enumerated() {
                    let imageFrame = editInfo.imageInfos[i].imageFrame
                    let viewFrame = CGRect(x: imageFrame.origin.x * scale, y: imageFrame.origin.y * scale + offsetImageY, width: imageFrame.width * scale, height: imageFrame.height * scale)
                    subView.frame = viewFrame
                }
            }
        }
        lastSize = frame.size
    }
    
    private func addImageViews(){
        if frame.size != .zero,let editInfo = editInfo {
            let viewRatio = frame.size.width / frame.size.height
            //宽铺满，image的Frame转化为view的Frame，并且计算模板图和view的高度差，需要位移居中
            let offsetImageY = (WALLPAPER_TEMPLATE_RATIO - viewRatio) * WALLPAPER_TEMPLATE_WIDTH / 2
            let scale = frame.size.width / WALLPAPER_TEMPLATE_WIDTH
            for (i,imageInfo) in editInfo.imageInfos.enumerated() {
                let imageFrame = imageInfo.imageFrame
                let viewFrame = CGRect(x: imageFrame.origin.x * scale, y: imageFrame.origin.y * scale + offsetImageY, width: imageFrame.width * scale, height: imageFrame.height * scale)
                
                let subView = WallpaperImageContainerView(i)
                subView.setImageInfo(imageInfo)
                subView.frame = viewFrame
                let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onImageTap(_:)))
                subView.addGestureRecognizer(tapGesture)
                imageContainerList.append(subView)
                subViewParent.addSubview(subView)
            }
        }
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setImage(index:Int,image:UIImage){
        if let editInfo = editInfo{
            let imageInfo = editInfo.imageInfos[index]
            imageInfo.showImage = image
            if index < imageContainerList.count {
                imageContainerList[index].setImageInfo(imageInfo)
            }
        }
    }
    
    // MARK: - Gesture Recognizer Actions
    @objc private func onEmptyViewTap(_ tapGesture: UITapGestureRecognizer) {
        debugPrint("onEmptyViewTap")
        editingImageContainer = nil
    }
    
    @objc private func onImageTap(_ tapGesture: UITapGestureRecognizer) {
        debugPrint("onImageTap")
        if tapGesture.view is WallpaperImageContainerView {
            let view = tapGesture.view as! WallpaperImageContainerView
            let index = view.index
            let imageInfo = editInfo!.imageInfos[index]
            if imageInfo.showImage == nil {
                onAddImage?(view.index)
            }else{
                editingImageContainer = view
            }
        }
    }
    
    @objc private func rotateAction(_ rotateGesture: UIRotationGestureRecognizer) {
        guard rotateGesture.numberOfTouches > 1 else {
            return
        }
        controlView.rorateView(rotateGesture.rotation)
        rotateGesture.rotation = 0
    }
    
    @objc private func panGestureAction(_ panGesture: UIPanGestureRecognizer) {
        guard panGesture.state == .changed else { return }
        guard panGesture.numberOfTouches <= 1 else {
            panGesture.setTranslation(.zero, in: superview)
            return
        }
        let translation = panGesture.translation(in: superview)
        controlView.translationView(x: translation.x, y: translation.y)
        panGesture.setTranslation(.zero, in: superview)
    }
    
    @objc private func pinchAction(_ pinchGesture: UIPinchGestureRecognizer) {
        guard pinchGesture.numberOfTouches > 1 else { return }
        let scale = pinchGesture.scale
        if controlView.scaleView(scale){
            controlView.onTransformUpate?()
        }
        pinchGesture.scale = 1
    }
}

// MARK: - UIGestureRecognizerDelegate

extension WallpaperEditView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
